﻿using UnityEngine;
using UnityEngine.EventSystems;

namespace winS.Unity
{
    /// <summary>
    /// 提供对 <see cref="UnityEngine.EventSystems.EventSystem"/> 的管理
    /// </summary>
    public class EventSystem
    {
        public BaseInputModule inputModule => GetInputModule();

        private bool enabled;

        private BaseInputModule _inputModule;

        /// <summary>
        /// 启用事件系统.
        /// 这会创建 <see cref="UnityEngine.EventSystems.EventSystem"/> 和 <see cref="StandaloneInputModule"/>
        /// </summary>
        public void Enable()
        {
            if (enabled) return;
            enabled = true;

            GameObject gameObject = new GameObject("Event System");
            gameObject.hideFlags = HideFlags.HideInHierarchy;
            gameObject.AddComponent<UnityEngine.EventSystems.EventSystem>();
            _inputModule = gameObject.AddComponent<StandaloneInputModule>();
            Object.DontDestroyOnLoad(gameObject);
        }

        public T ReplaceInputModule<T>() where T : BaseInputModule
        {
            Enable();
            GameObject gameObject = inputModule.gameObject;
            Object.Destroy(inputModule);
            T newInputModule = gameObject.AddComponent<T>();
            _inputModule = newInputModule;
            return newInputModule;
        }

        private BaseInputModule GetInputModule()
        {
            Enable();
            return _inputModule;
        }
    }
}